package cn.chencq.memcached.demo;

import java.util.Date;
import java.util.Map;

import com.danga.MemCached.MemCachedClient;
import com.danga.MemCached.SockIOPool;

public class MemcachedManager {

	protected static MemCachedClient mcc = new MemCachedClient();

	static {
		String[] servers = { "127.0.0.1:11211", "127.0.0.1:11212" };

		Integer[] weights = { 3, 4 };

		SockIOPool pool = SockIOPool.getInstance();

		pool.setServers(servers);
		pool.setWeights(weights);

		pool.setInitConn(5);
		pool.setMinConn(5);
		pool.setMaxConn(200);
		pool.setMaxIdle(1000 * 60 * 60 * 5);

		pool.setMaintSleep(30);

		pool.setNagle(false);
		pool.setSocketTO(3000);
		pool.setSocketConnectTO(0);

		pool.initialize();

	}

	// 受保护的对象
	protected static MemcachedManager instance = new MemcachedManager();

	/**
	 * 无参构造
	 */
	protected MemcachedManager() {

	}

	/**
	 * 为受保护的对象提供一个公共的访问方法
	 */
	public static MemcachedManager getInstance() {
		return instance;
	}

	/**
	 * 添加对象到缓存中
	 * @param key 键
	 * @param value 值
	 * @return
	 */
	public boolean add(String key, Object value) {
		return mcc.add(key, value);
	}

	/**
	 * 添加对象到缓存中
	 * @param key 键
	 * @param value 值
	 * @param expiry 有效期
	 * @return
	 */
	public boolean add(String key, Object value, Date expiry) {
		return mcc.add(key, value, expiry);
	}

	/**
	 * 替换或修改某个键的值
	 * @param key 键
	 * @param value 值
	 * @return
	 */
	public boolean replace(String key, Object value) {
		return mcc.replace(key, value);
	}

	/**
	 *  替换或修改某个键的值
	 * @param key 键
	 * @param value 值
	 * @param expiry 有效期
	 * @return
	 */
	public boolean replace(String key, Object value, Date expiry) {
		return mcc.replace(key, value, expiry);
	}

	/**
	 * 创建或修改某个键值对
	 * @param key
	 * @param value
	 * @return
	 */
	public boolean set(String key, Object value) {
		return mcc.set(key, value);
	}

	/**
	 * 创建或修改某个键值对
	 * @param key
	 * @param value
	 * @param expiry
	 * @return
	 */
	public boolean set(String key, Object value, Date expiry) {
		return mcc.set(key, value, expiry);
	}

	/**
	 * 根据指定的关键字获取对象
	 */
	public Object get(String key) {
		return mcc.get(key);
	}

	/**
	 * 获取多个缓存对象
	 * @param keys
	 * @return
	 */
	public Map<String, Object> getMulti(String[] keys) {
		return mcc.getMulti(keys);
	}

	/**
	 * 删除某个缓存对象
	 * @param key
	 * @return
	 */
	public boolean delete(String key) {
		return mcc.delete(key);
	}

	/**
	 * 刷新全部缓存
	 */
	public boolean flushAll() {
		return mcc.flushAll();
	}

	/**
	 * 增加值的大小
	 * 值的范围【0~2^32-1】
	 * @param key
	 * @param l
	 * @return
	 */
	public long incr(String key, long l) {
		return mcc.incr(key, l);
	}

	/**
	 * 减小值的大小
	 * 值的范围【0~2^32-1】
	 * @param key
	 * @param l
	 * @return
	 */
	public long decr(String key, long l) {
		return mcc.decr(key, l);
	}

}
